from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from core.database import get_db
from core.logger import log
from core.security import get_current_user_m
from db.mysql.users import Users
from db.pydantic.request.call_task import CallTasksCreateRequest, CallTaskCustomerRequest, \
    CallTaskCustomerUpdateRequest, CallTasksListRequest
from services.call_task_service import get_call_task_service
from utils.result import Result

router = APIRouter(prefix="/call/tasks", tags=["call_tasks"])

@router.post("/create")
async def create_call_tasks(req:CallTasksCreateRequest,db:Session = Depends(get_db),current_user: Users = Depends(get_current_user_m)):
    """
    创建通话任务
    参数：{
        customer_ids?: int[],    // 选中的客户ID列表（可选）
        random_count?: int,      // 随机选择数量（可选，30/50/100/200）
        task_name?: string          // 任务名称（可选）
    }
    返回: {
        task_id: int,
        total_count: int,
        message: string
    }
    """
    call_service = get_call_task_service()
    responses = await call_service.create_call_task(req,db,current_user)
    if responses:
        return Result.success(responses)
    return Result.fail(msg="创建通话任务失败")

@router.get("/list")
async def list_call_tasks(req:CallTasksListRequest= Depends(),db:Session = Depends(get_db),current_user: Users = Depends(get_current_user_m)):
    """
    列出通话任务
    参数: {
    page: number,
    page_size: number,
    status?: string,           // 任务状态过滤
    created_by?: string        // 创建人过滤
}
返回: {
    tasks: [
        {
            id: string,
            task_name: string,
            total_count: number,
            remaining_count: number,
            status: string,
            created_by: string,
            created_at: string,
            started_at: string,
            completed_at: string
        }
    ],
    total: number
}
    """
    call_service = get_call_task_service()
    responses = await call_service.list_call_task(req,db,current_user)
    if responses:
        return Result.success(responses)
    return Result.fail(msg="列出通话任务失败")

@router.get("/{task_id}/customers")
async def list_call_task_customers(task_id: int,req:CallTaskCustomerRequest=Depends(),db = Depends(get_db)):

    """
    轮呼任务详情接口
        参数: {
            page: number,
            page_size: number,
            call_status?: string // 轮呼状态过滤
        }
        返回: {
            customers: [
                {
                    id: string,
                    customer_name: string,
                    phone: string,
                    customer_type: string,
                    call_status: string,
                    call_result: string,
                    call_time: string
                }
            ],
            total: number,
            task_info: {
                id: string,
                task_name: string,
                total_count: number,
                remaining_count: number,
                status: string
            }
        }"""
    call_service = get_call_task_service()
    responses = await call_service.list_call_task_customer(task_id,req,db)
    if responses:
        return Result.success(responses)
    return Result.fail(msg="列出通话任务详情失败")

@router.post("/{task_id}/start")
async def start_call_task(task_id: str,db:Session = Depends(get_db)):
    """
    启动通话任务
    参数: {
        task_id: string
    }
    返回: {
        message: string
    }
    """
    try:
        call_service = get_call_task_service()
        await call_service.start_task(task_id,db)
        return Result.success(msg="启动通话任务成功")
    except Exception as e:
        return Result.fail(msg="启动通话任务失败")


@router.post("/{task_id}/customers/{customer_id}/status")
async def update_call_task_customer_status(task_id: str, customer_id: str, req: CallTaskCustomerUpdateRequest,db:Session = Depends(get_db)):
    """
     更新客户轮呼状态接口
    参数: {
    call_status: string,       // 'pending','dialing','connected','ended','completed','failed'
    call_result?: string       // 轮呼结果
}
    返回: {
        message: string
    }
    """
    try:
        call_service = get_call_task_service()
        responses = await call_service.update_task_customer_status(task_id, customer_id, req, db)
        return Result.success(data=responses)
    except Exception as e:
        return Result.fail(msg="更新客户轮呼状态失败")


@router.post("/{task_id}/cancel")
async def cancel_call_task(task_id: str,db:Session = Depends(get_db)):
    """
    取消任务
    参数: {
        task_id: string
    }
    返回: {
        message: string
    }
    """
    try:
        call_service = get_call_task_service()
        responses =await call_service.cancel_task(task_id,db)
        return Result.success(data=responses)
    except Exception as e:
        log.error( f"当前是call_tasks_router.py中完成通话任务接口出现问题{str(e)}")
        return Result.fail(msg="完成通话任务失败")

@router.post("/{task_id}/stop")
async def stop_call_task(task_id: str,db:Session = Depends(get_db)):
    try:
        call_service = get_call_task_service()
        responses =await call_service.stop_task(task_id,db)
        return Result.success(data=responses)
    except Exception as e:
        log.error( f"当前是call_tasks_router.py中完成通话任务接口出现问题{str(e)}")
        return Result.fail(msg="完成通话任务失败")

